/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package ant.antsys;

import java.io.File;

import org.apache.tools.ant.BuildException;

/**
 * Assertion class to verify file content using regular expression
 * @author johnson ma
 */
public class AssertFileGrep extends AssertFail {

	private String file;
	private String regExp;

	// The method executing the task
	public void execute() throws BuildException {
		//check if the file exists
		File fileToCheck = new File(file);
		if (!fileToCheck.exists()) {
			BuildException be = new BuildException("file doesn't exists:"
					+ fileToCheck);
			throw be;
		}
		try {
			String found = Grep.grep(fileToCheck, regExp);
			if (negative) {
				if (found != null) {
					String msg = errorMsg == null ? "AssertFileGrep: not expected:"
							+ regExp + "file:" + file
							: errorMsg;
					BuildException be = new BuildException(msg);
					throw be;
				}

			} else {
				if (found == null) {
					String msg = errorMsg == null ? "AssertFileGrep: expected:"
							+ regExp + " file:" + file : errorMsg;
					BuildException be = new BuildException(msg);
					throw be;
				}
			}
		} catch (Exception ioe) {
			throw new BuildException(ioe, getLocation());
		}
	}

	public void setFile(String file) {
		this.file = file;
	}

	public String getFile() {
		return file;
	}

	public void setRegExp(String regExp) {
		this.regExp = regExp;
	}

	public String getRegExp() {
		return regExp;
	}

}
